import json
import os

class ConfigReader:
    """配置文件读取器，用于加载和管理应用程序配置"""
    
    _instance = None
    _config = None
    
    def __new__(cls, config_file='config.json'):
        """单例模式实现，确保全局只有一个配置实例"""
        if cls._instance is None:
            cls._instance = super(ConfigReader, cls).__new__(cls)
            cls._config = cls._instance._load_config(config_file)
        return cls._instance
    
    def __init__(self, config_file='config.json'):
        """初始化配置读取器"""
        # 由于使用单例模式，初始化方法可能会被多次调用，但我们只需要加载一次配置
        pass
    
    def _load_config(self, config_file):
        """从配置文件中加载配置"""
        if os.path.exists(config_file):
            try:
                with open(config_file, 'r', encoding='utf-8') as f:
                    config = json.load(f)
                    # print(f"成功加载配置文件: {config_file}")
                    return config
            except json.JSONDecodeError as e:
                print(f"解析配置文件失败: {e}")
                return self._get_default_config()
            except Exception as e:
                print(f"读取配置文件时发生错误: {e}")
                return self._get_default_config()
        else:
            print(f"配置文件 {config_file} 不存在，使用默认配置")
            return self._get_default_config()
    
    def _get_default_config(self):
        """获取默认配置"""
        return {
            "database": {
                "host": "localhost",
                "port": 3306,
                "user": "root",
                "password": "",
                "db_name": "asset"
            },
            "application": {
                "log_level": "INFO",
                "max_retries": 3
            },
            "export": {
                "folder": "export",
                "max_file_size": 1024 * 1024 * 100  # 100MB
            },
            "import": {
                "max_file_size": 1024 * 1024 * 10  # 10MB
            }
        }
    
    def get(self, key, default=None):
        """获取配置项，支持点号分隔的嵌套路径"""
        if self._config is None:
            return default
        
        # 支持点号分隔的嵌套路径访问，如 "database.host"
        if '.' in key:
            keys = key.split('.')
            value = self._config
            for k in keys:
                if isinstance(value, dict) and k in value:
                    value = value[k]
                else:
                    return default
            return value
        
        # 直接访问顶层配置项
        return self._config.get(key, default)
    
    def get_database_config(self):
        """获取数据库相关配置"""
        return self.get('database', {})
    
    def get_application_config(self):
        """获取应用程序相关配置"""
        return self.get('application', {})
    
    def get_export_config(self):
        """获取导出配置"""
        return self.get('export', {})
    
    def get_import_config(self):
        """获取导入配置"""
        return self.get('import', {})

# 创建一个全局可访问的配置实例
config = ConfigReader()

# 提供便捷的函数来获取配置
def get_config():
    """获取配置实例"""
    return config

def get(key, default=None):
    """便捷函数：获取配置项"""
    return config.get(key, default)

def get_database_config():
    """便捷函数：获取数据库配置"""
    return config.get_database_config()

def get_application_config():
    """便捷函数：获取应用程序配置"""
    return config.get_application_config()

def get_export_config():
    """便捷函数：获取导出配置"""
    return config.get_export_config()

def get_import_config():
    """便捷函数：获取导入配置"""
    return config.get_import_config()